<?php

namespace app\admin\model\fastflow\flow;

use app\admin\model\Admin;
use fastflow\api;
use think\Config;
use think\Db;
use think\Model;


class Process extends Model
{


    // 表名
    protected $name = 'fastflow_process';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'flow_name',
        'bill_comment',
        'flow_progress',
        'initiator',
        'bill_status',
        'bill_name',
    ];


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getFlowNameAttr($value, $data)
    {
        $flow = (new api())->getFlow($data['flow_id'], true);
        if (!$flow) {
            return '-';
        }
        return $flow['name'];
    }

    public function getBillCommentAttr($value, $data)
    {
        $tables = Db::query("select TABLE_NAME as name,TABLE_COMMENT as comment from information_schema.tables where table_schema='" . Config::get('database')['database'] . "'");
        $bill_comment = '';
        for ($i = 0; $i < count($tables); $i++) {
            if ($tables[$i]['name'] == $data['bill']) {
                $bill_comment = $tables[$i]['comment'];
                break;
            }
        }
        return $bill_comment;
    }

    public function getFlowProgressAttr($value, $data)
    {
        return (new api())->getFlowProgress($data['bill'], $data['bill_id']);
    }

    public function getInitiatorAttr($value, $data)
    {
        $bill_row = (new api())->getBillRow($data['bill'], $data['bill_id']);
        if (!$bill_row) {
            return '';
        }
        $createUserId = $bill_row['initiator_id'];
        $user = Admin::find($createUserId);
        if ($user) {
            return $user['nickname'];
        }
        return '';
    }

    public function getBillStatusAttr($value, $data)
    {
        $bill_row = (new api())->getBillRow($data['bill'], $data['bill_id']);
        if (!$bill_row) {
            return 0;
        }
        return 1;
    }

    public function getBillNameAttr($value, $data)
    {
        return (new api())->getTableComment($data['bill']);
    }

    public function getStatisticData()
    {
        $rows = $this->select();
        $statistic_data = [];
        foreach ($rows as $row) {
            if (!isset($statistic_data[$row['bill']])) {
                $statistic_data[$row['bill']] = [
                    'total'       => 0,
                    'run'         => 0,
                    'finish'      => 0,
                    'termination' => 0,
                    'comment'     => $row['bill'],
                ];

            }
            $tables = Db::query("select TABLE_NAME as name,TABLE_COMMENT as comment from information_schema.tables where table_schema='" . Config::get('database')['database'] . "'");
            for ($i = 0; $i < count($tables); $i++) {
                if ($tables[$i]['name'] == $row['bill']) {
                    $statistic_data[$row['bill']]['comment'] = $tables[$i]['comment'] == '' ? $tables[$i]['name'] : $tables[$i]['comment'];
                    break;
                }
            }
            $statistic_data[$row['bill']]['total'] += 1;
            if ($row['status'] == 1) {
                $statistic_data[$row['bill']]['run'] += 1;
            } elseif ($row['status'] == 2) {
                $statistic_data[$row['bill']]['finish'] += 1;
            } elseif ($row['status'] == 3) {
                $statistic_data[$row['bill']]['termination'] += 1;
            }
        }

        return $statistic_data;
    }

    public function getChartData()
    {
        $statistic_data = $this->getStatisticData();
        $yAxis_data = [];
        $finish_data = [];
        $termination_data = [];
        $run_data = [];
        foreach ($statistic_data as $key => $data) {
            $yAxis_data[] = isset($data['comment']) ? $data['comment'] : $key;
            $finish_data[] = $data['finish'];
            $termination_data[] = $data['termination'];
            $run_data[] = $data['run'];
        }
        return ['yAxis_data' => $yAxis_data, 'finish_data' => $finish_data, 'termination_data' => $termination_data, 'run_data' => $run_data];
    }

    public function getTotalData()
    {
        $rows = $this->select();
        $total = 0;
        $finish = 0;
        $termination = 0;
        $run = 0;
        foreach ($rows as $row) {
            if ($row['status'] == 1) {
                $run += 1;
            } elseif ($row['status'] == 2) {
                $finish += 1;
            } elseif ($row['status'] == 3) {
                $termination += 1;
            }
            $total += 1;
        }
        return ['total' => $total, 'finish' => $finish, 'termination' => $termination, 'run' => $run];
    }

    public function getRecentThreadLog()
    {
        //获取近7天数据
        $startDate = mktime(0, 0, 0, date('m'), date('d') - 6, date('Y'));
        $endDate = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $thread_logs = (new ThreadLog())->where('createtime', 'between time', [$startDate, $endDate])->order('createtime', 'desc')->select();
        $bills = (new Bill())->select();
        $check_type = [1 => '同意', 2 => '驳回', 3 => '会签', 4 => '终止', 5 => '发起', 6 => '结束'];
        foreach ($thread_logs as &$log) {
            $bill = $log['bill'];
            $log['hasbill'] = false;
            $log['createtime'] = date('Y-m-d H:i:s', $log['createtime']);
            $log['check_behavior'] = $check_type[$log['check_type']];
            $log['bill_name'] = $log['bill'];
            for ($i = 0; $i < count($bills); $i++) {
                if ($bills[$i]['bill_table'] == $bill) {
                    $log['hasbill'] = true;
                    $log['bill_name'] = $bills[$i]['bill_name'] == '' ? $bill : $bills[$i]['bill_name'];
                    break;
                }
            }
        }
        return $thread_logs;
    }

    public function getRecentCount()
    {
        $recentData = [
            'today' => ['start' => 0, 'work' => 0, 'done' => 0],
            'week'  => ['start' => 0, 'work' => 0, 'done' => 0],
            'month' => ['start' => 0, 'work' => 0, 'done' => 0],
        ];

        $todayStart = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $weekStart = mktime(0, 0, 0, date('m'), (date('d') - (date('w') > 0 ? date('w') : 7) + 1), date('Y'));
        $monthStart = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $todayEnd = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

        $today_logs = (new ThreadLog())->where('createtime', 'between time', [$todayStart, $todayEnd])->select();
        $week_logs = (new ThreadLog())->where('createtime', 'between time', [$weekStart, $todayEnd])->select();
        $month_logs = (new ThreadLog())->where('createtime', 'between time', [$monthStart, $todayEnd])->select();

        $rangelogs = [$today_logs, $week_logs, $month_logs];
        $rangeText = ['today', 'week', 'month'];
        $index = 0;
        array_map(function ($rangelog) use ($rangeText, &$index, &$recentData) {
            array_map(function ($log) use ($rangeText, &$index, &$recentData) {
                switch ($log['check_type']) {
                    case '1':
                    case '2':
                    case '3':
                        $recentData[$rangeText[$index]]['work'] += 1;
                        break;
                    case '4':
                    case '6':
                        $recentData[$rangeText[$index]]['done'] += 1;
                        break;
                    case '5':
                        $recentData[$rangeText[$index]]['start'] += 1;
                        break;
                }
            }, $rangelog);
            $index += 1;
        }, $rangelogs);
        return $recentData;
    }
}
